package com.vip.jwt.config;

import com.vip.jwt.common.exception.ExceptionEnum;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @author vip
 * @date 2020-5-5 11:23
 */
public class XCXRealm extends AuthorizingRealm {

    @Autowired
    private HttpServletRequest request;

    /*
     * 多重写一个support
     * 标识这个Realm是专门用来验证JwtToken
     * 不负责验证其他的token（UsernamePasswordToken）
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String)authenticationToken.getPrincipal();
        String username = JwtUtil.getUsername(token);
        if(null == username){
            //抛异常 token验证错误
            throw new MyException(ExceptionEnum.TOKEN_INVALID);
        }
        //todo 根据用户名在数据库查找用户，如果用户为空，则用户不存在
        String password = "456";
        boolean verify = JwtUtil.verify(request,username,password);
        if(!verify){
            //todo 用户名或者密码错误
        }
        return new SimpleAuthenticationInfo(token,token,getName());
    }

}
